package com.v9.main.controller.common;

import com.v9.common.config.GlobalConfig;
import com.v9.common.utils.file.FileUploadUtils;
import com.v9.common.utils.file.FileUtils;
import com.v9.common.web.AbstractController;
import com.v9.system.config.ServerConfig;
import com.v9.system.domain.UploadInfo;
import com.v9.system.mapper.UploadInfoMapper;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/common")
public class CommonController extends AbstractController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private ServerConfig serverConfig;
    @Resource
    private GlobalConfig globalConfig;

    @Resource
    private UploadInfoMapper uploadInfoMapper;


    private static final String FILE_DELIMETER = ",";

    @Resource
    private RedisTemplate redisTemplate;


    @GetMapping("/upload/{year}/{month}/{day}/{file}")
    public void fileDownload(@PathVariable String year,@PathVariable String month,@PathVariable String day,@PathVariable String file) throws IOException {
        String filePath = GlobalConfig.getUploadPath();
        //以字节流输出文件
        InputStream is = new FileInputStream(filePath + year+"/"+month+"/"+day+"/"+file);
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } finally {
            IOUtils.close(os);
            IOUtils.close(is);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public Map<String, Object> uploadFile(MultipartFile file) throws Exception {
        return buildMessage(() -> {
            // 上传文件路径
            String filePath = GlobalConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = "common/upload/" + fileName;
            Map<String, Object> result = new HashMap<>();
            result.put("url", url);
            result.put("name", file.getOriginalFilename());
            UploadInfo entity = new UploadInfo();
            entity.setName(file.getOriginalFilename());
            entity.setFileTypeCode(FileUtils.getFileType(file.getBytes()));
            entity.setPath(fileName);
            entity.setFileSize(BigDecimal.valueOf(file.getSize()));
            entity.setCreateTime(new Date());
            entity.setUpdateTime(entity.getCreateTime());
            redisTemplate.opsForValue().set("system:upload:" + fileName, entity);
            uploadInfoMapper.insert(entity);
            return result;
        });
    }
//
//    /**
//     * 通用上传请求（多个）
//     */
//    @PostMapping("/uploads")
//    public Map<String, Object> uploadFiles(List<MultipartFile> files) {
//        return buildMessage(()->{
//            // 上传文件路径
//            String filePath = GlobalConfig.getProfile();
//            List<String> urls = new ArrayList<String>();
//            List<String> fileNames = new ArrayList<String>();
//            List<String> newFileNames = new ArrayList<String>();
//            List<String> originalFilenames = new ArrayList<String>();
//            for (MultipartFile file : files) {
//                // 上传并返回新文件名称
//                String fileName = FileUploadUtils.upload(filePath, file);
//                String url = serverConfig.getUrl() + fileName;
//                urls.add(url);
//                fileNames.add(fileName);
//                newFileNames.add(FileUtils.getName(fileName));
//                originalFilenames.add(file.getOriginalFilename());
//            }
//            Map<String, Object> result = new HashMap<>();
//            result.put("urls", StringUtils.join(urls, FILE_DELIMETER));
//            result.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
//            result.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
//            result.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
//            return result;
//        });
//    }
//
//    /**
//     * 本地资源通用下载
//     */
//    @GetMapping("/download/resource")
//    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
//            throws Exception {
//        try {
//            if (!FileUtils.checkAllowDownload(resource)) {
//                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
//            }
//            // 本地资源路径
//            String localPath = GlobalConfig.getProfile();
//            // 数据库资源地址
//            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
//            // 下载名称
//            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
//            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//            FileUtils.setAttachmentResponseHeader(response, downloadName);
//            FileUtils.writeBytes(downloadPath, response.getOutputStream());
//        } catch (Exception e) {
//            log.error("下载文件失败", e);
//        }
//    }
}
